package com.engine.shunsheng.service.impl;

import cn.hutool.core.date.DateUtil;
import com.engine.core.impl.Service;
//import com.engine.salary.util.report.SalaryReportUtil;
import com.engine.shunsheng.service.SalaryService;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author chenwnj
 * @date 2023/11/16
 * @description
 **/
public class SalaryServiceImpl extends Service implements SalaryService {
    BaseBean bb = new BaseBean();
    @Override
    public Map<String, Object> getSalaryInfo(Map<String, Object> params) {
        bb.writeLog("---------getSalaryInfo start---------");

        Map<String, Object> result = new HashMap<>();

        String token = Util.null2String(params.get("token"));
        bb.writeLog("token: " + token);
        String year = Util.null2String(params.get("year"));
        bb.writeLog("year: " + year);
        String month = Util.null2String(params.get("month"));
        bb.writeLog("month: " + month);

        if (StringUtils.isBlank(token)) {
            result.put("success","false");
            result.put("message","请求token不可为空");
            return result;
        }
        if (StringUtils.isBlank(year)) {
            result.put("success","false");
            result.put("message","请求年份不可为空");
            return result;
        }
        if (StringUtils.isBlank(month)) {
            result.put("success","false");
            result.put("message","请求月份不可为空");
            return result;
        }


        RecordSet rs = new RecordSet();
        String effectiveToken = "";
        String nowDay = DateUtil.format(new Date(), "yyyy-MM-dd");
        bb.writeLog("nowDay: " + nowDay);

        String acqTokenSql = "select top 1 token from uf_salarytoken where (isdelete = 1 or isdelete is null) and effectivedate <= '" + nowDay + "' order by effectivedate desc";
        bb.writeLog("acqTokenSql: " + acqTokenSql);

        rs.executeQuery(acqTokenSql);
        while (rs.next()) {
            effectiveToken = Util.null2String(rs.getString("token"));
        }
        bb.writeLog("effectiveToken: " + effectiveToken);

        if ( StringUtils.isBlank(effectiveToken)) {
            result.put("success","false");
            result.put("message","OA未设置有效token");
            return result;
        }

        if ( !effectiveToken.equals(token)) {
            result.put("success","false");
            result.put("message","无效token，请更换有效的token");
            return result;
        }

        //获取地区过滤条件
        String condition = "";
        String acqCondSql = "select csdxzzt from uf_xztzsz ";
        rs.executeQuery(acqCondSql);
        if (rs.next()) {
            condition = Util.null2String(rs.getString("csdxzzt"));
        }
        String sqlWhere = "";
        if (StringUtils.isNotBlank(condition)) {
            sqlWhere = " and t1.salary_sob_id in (" + condition + ") ";
        }

        //业务处理
        //获取薪酬信息
        List<Map<String, String>> salaryList = new ArrayList<>();
        String acqSalarySql = "SELECT " +
                "t5.subcompanycode,t5.subcompanyname,t4.departmentcode,t4.id as departmentid,t1.result_value ,t1.salary_item_id, t1.salary_acct_record_id, " +
                "t1.salary_sob_id, " +
                "case t3.field13 when 1 then 'B' else 'A' end as gjlb, t7.salary_month, " +
                "t6.jdxzxmbm,t6.jdxzxmmc " +
                "FROM hrsa_salary_acct_result t1 " +
                "left join hrmresource t2  " +
                "on t2.id= t1.employee_id  " +
                "left join cus_fielddata t3  " +
                "on t3.scopeid = 1 and t3.id = t1.employee_id  " +
                "left join hrmdepartment t4  " +
                "on t4.id = t2.departmentid  " +
                "left join HrmSubCompany t5  " +
                "on t5.id = t2.subcompanyid1  " +
                "left join uf_xczdys t6  " +
                "on t6.fwxzxmid = t1.salary_item_id  " +
                "left join hrsa_salary_acct_record t7 " +
                "on t7.id = t1.salary_acct_record_id " +
                "WHERE t6.id is not null " +
                "and DATEPART(YEAR, t7.salary_month) ="+year+
                " and DATEPART(month, t7.salary_month) ="+month + sqlWhere;
        bb.writeLog("acqSalarySql: " + acqSalarySql);

        rs.executeQuery(acqSalarySql);
        while (rs.next()) {
            String subcompanyCode = Util.null2String(rs.getString("subcompanycode"));
            String subcompanyName = Util.null2String(rs.getString("subcompanyname"));
            String departmentCode = Util.null2String(rs.getString("departmentcode"));
            String departmentId = Util.null2String(rs.getString("departmentid"));
            String resultValue = Util.null2String(rs.getString("result_value"));
            String salaryItemId = Util.null2String(rs.getString("salary_item_id"));
            String salaryAcctRecordId = Util.null2String(rs.getString("salary_acct_record_id"));
            String gjlb = Util.null2String(rs.getString("gjlb"));
            String jdxzxmbm = Util.null2String(rs.getString("jdxzxmbm"));
            String jdxzxmmc = Util.null2String(rs.getString("jdxzxmmc"));

            Map<String, String> salaryMap= new HashMap<>();
            //解密
            String decryptValue = null;

            salaryMap.put("shcq_amount",decryptValue);
            salaryMap.put("salary_acct_record_id",salaryAcctRecordId);
            salaryMap.put("shcq_costnumber",jdxzxmbm);
            salaryMap.put("shcq_costname",jdxzxmmc);
            salaryMap.put("shcq_costorg",departmentCode);
            salaryMap.put("shcq_ascription",gjlb);
            salaryMap.put("shcq_xcxm",jdxzxmbm);
            salaryMap.put("shcq_orgnumber",subcompanyCode);//薪酬组织编码
            salaryMap.put("shcq_org",subcompanyName);//薪酬组织名称
            salaryList.add(salaryMap);

        }

        bb.writeLog("salaryList: " + salaryList);
        int size = salaryList.size();
        bb.writeLog("salaryList size: " + salaryList.size());


        bb.writeLog("salaryList start to do for()");

        List<Map<String,Object>> querydata = new ArrayList<>();
        try {

            int i = -1;
            Map<String,Object> subSalaryMap = new HashMap<>();
            for (Map<String, String> salary:salaryList) {
                i++;
                bb.writeLog("i: " + i);
                bb.writeLog("querydata.size(): " + querydata.size());
                if (i > size) {
                    bb.writeLog(" 循环过多，跳出 ");
                    break;
                }
                String shcqOrgnumber = salary.get("shcq_orgnumber");
                String salaryAcctRecordId = salary.get("salary_acct_record_id");
//                bb.writeLog("--shcq_orgnumber: " + shcqOrgnumber);

                if (querydata !=null && querydata.size() > 0) {
                    boolean addFlag = false;
                    boolean doneFlag = false;
                    for (Map<String,Object> data: querydata) {
                        String number = Util.null2String(data.get("number"));
//                        bb.writeLog("--number: " + number);

                        String shcqTotalamount = Util.null2String(data.get("shcq_totalamount"));
                        String salaryAcctRecordIdGet = Util.null2String(data.get("salary_acct_record_id"));
//                        bb.writeLog("--shcqTotalamount: " + shcqTotalamount);

                        if (number.equals(shcqOrgnumber) ) {
                            if ( salaryAcctRecordIdGet.equals(salaryAcctRecordId)) {
                                List<Map<String, String>> shcqEntryentity = (List<Map<String, String>>) data.get("shcq_entryentity");

                                String shcqAmount = salary.get("shcq_amount");
                                if (StringUtils.isBlank(shcqAmount)) {
                                    shcqAmount = "0.00";
                                }
//                            bb.writeLog("--shcq_amount: " + shcqAmount);

                                String shcqCostnumber = salary.get("shcq_costnumber");
//                            bb.writeLog("--shcq_costnumber: " + shcqCostnumber);

                                String shcqCostname = salary.get("shcq_costname");
//                            bb.writeLog("--shcq_costname: " + shcqCostname);

                                String shcqCostorg = salary.get("shcq_costorg");
//                            bb.writeLog("--shcq_costorg: " + shcqCostorg);

                                String shcqAscription = salary.get("shcq_ascription");
//                            bb.writeLog("--shcq_ascription: " + shcqAscription);

                                String shcqXcxm = salary.get("shcq_xcxm");
//                            bb.writeLog("--shcq_xcxm: " + shcqXcxm);

                                Map<String, String> shcqEntryentityMap = new HashMap<>();
                                shcqEntryentityMap.put("shcq_amount", shcqAmount);
                                shcqEntryentityMap.put("shcq_costnumber", shcqCostnumber);
                                shcqEntryentityMap.put("shcq_costname", shcqCostname);
                                shcqEntryentityMap.put("shcq_costorg", shcqCostorg);
                                shcqEntryentityMap.put("shcq_ascription", shcqAscription);
                                shcqEntryentityMap.put("shcq_xcxm", shcqXcxm);
//                            bb.writeLog("--shcqEntryentityMap: " + shcqEntryentityMap);

                                shcqEntryentity.add(shcqEntryentityMap);
//                            bb.writeLog("--shcqEntryentity: " + shcqEntryentity);

                                shcqTotalamount = (new BigDecimal(shcqTotalamount).add(new BigDecimal(shcqAmount))).toString();
//                            bb.writeLog("--shcqTotalamount: " + shcqTotalamount);

                                data.put("shcq_totalamount", shcqTotalamount);
                                doneFlag = true;
                            }
                        } else {
                            addFlag = true;
//                            bb.writeLog("--addFlag: " + addFlag);
                        }
                    }

                    if ( addFlag) {
                        subSalaryMap = new HashMap<>();

                        String number = salary.get("shcq_orgnumber");
//                        bb.writeLog("--number: " + number);

                        String shcqOrg = salary.get("shcq_org");
//                        bb.writeLog("--shcqOrg: " + shcqOrg);

                        String shcqAmount = salary.get("shcq_amount");
//                        bb.writeLog("--shcqAmount: " + shcqAmount);
                        if (StringUtils.isBlank(shcqAmount)) {
                            shcqAmount = "0.00";
                        }

                        String shcqCostnumber = salary.get("shcq_costnumber");
//                        bb.writeLog("--shcqCostnumber: " + shcqCostnumber);

                        String shcqCostname = salary.get("shcq_costname");
//                        bb.writeLog("--shcqCostname: " + shcqCostname);

                        String shcqCostorg = salary.get("shcq_costorg");
//                        bb.writeLog("--shcqCostorg: " + shcqCostorg);

                        String shcqAscription = salary.get("shcq_ascription");
//                        bb.writeLog("--shcqAscription: " + shcqAscription);

                        String shcqXcxm = salary.get("shcq_xcxm");
//                        bb.writeLog("--shcqXcxm: " + shcqXcxm);

                        List<Map<String, String>> shcqEntryentityList = new ArrayList<>();
                        Map<String, String> shcqEntryentityMap = new HashMap<>();
                        shcqEntryentityMap.put("shcq_amount", shcqAmount);
                        shcqEntryentityMap.put("shcq_costnumber", shcqCostnumber);
                        shcqEntryentityMap.put("shcq_costname", shcqCostname);
                        shcqEntryentityMap.put("shcq_costorg", shcqCostorg);
                        shcqEntryentityMap.put("shcq_ascription", shcqAscription);
                        shcqEntryentityMap.put("shcq_xcxm", shcqXcxm);

                        shcqEntryentityList.add(shcqEntryentityMap);

                        subSalaryMap.put("number", number);
                        subSalaryMap.put("shcq_org", number);
                        subSalaryMap.put("shcq_totalamount", shcqAmount);
                        subSalaryMap.put("salary_acct_record_id", salaryAcctRecordId);
                        subSalaryMap.put("shcq_entryentity",shcqEntryentityList);

                        querydata.add(subSalaryMap);
                    } else if ( !doneFlag) {
                        subSalaryMap = new HashMap<>();

                        String number = salary.get("shcq_orgnumber");
//                        bb.writeLog("--number: " + number);

                        String shcqOrg = salary.get("shcq_org");
//                        bb.writeLog("--shcqOrg: " + shcqOrg);

                        String shcqAmount = salary.get("shcq_amount");
//                        bb.writeLog("--shcqAmount: " + shcqAmount);
                        if (StringUtils.isBlank(shcqAmount)) {
                            shcqAmount = "0.00";
                        }

                        String shcqCostnumber = salary.get("shcq_costnumber");
//                        bb.writeLog("--shcqCostnumber: " + shcqCostnumber);

                        String shcqCostname = salary.get("shcq_costname");
//                        bb.writeLog("--shcqCostname: " + shcqCostname);

                        String shcqCostorg = salary.get("shcq_costorg");
//                        bb.writeLog("--shcqCostorg: " + shcqCostorg);

                        String shcqAscription = salary.get("shcq_ascription");
//                        bb.writeLog("--shcqAscription: " + shcqAscription);

                        String shcqXcxm = salary.get("shcq_xcxm");
//                        bb.writeLog("--shcqXcxm: " + shcqXcxm);

                        List<Map<String, String>> shcqEntryentityList = new ArrayList<>();
                        Map<String, String> shcqEntryentityMap = new HashMap<>();
                        shcqEntryentityMap.put("shcq_amount", shcqAmount);
                        shcqEntryentityMap.put("shcq_costnumber", shcqCostnumber);
                        shcqEntryentityMap.put("shcq_costname", shcqCostname);
                        shcqEntryentityMap.put("shcq_costorg", shcqCostorg);
                        shcqEntryentityMap.put("shcq_ascription", shcqAscription);
                        shcqEntryentityMap.put("shcq_xcxm", shcqXcxm);

                        shcqEntryentityList.add(shcqEntryentityMap);

                        subSalaryMap.put("number", number);
                        subSalaryMap.put("shcq_org", number);
                        subSalaryMap.put("shcq_totalamount", shcqAmount);
                        subSalaryMap.put("salary_acct_record_id", salaryAcctRecordId);
                        subSalaryMap.put("shcq_entryentity",shcqEntryentityList);

                        querydata.add(subSalaryMap);
                    }

                } else {
                    subSalaryMap = new HashMap<>();

                    String number = salary.get("shcq_orgnumber");

                    String shcqAmount = salary.get("shcq_amount");
//                    bb.writeLog("--shcqAmount: " + shcqAmount);
                    if (StringUtils.isBlank(shcqAmount)) {
                        shcqAmount = "0.00";
                    }

                    String shcqOrg = salary.get("shcq_org");
//                    bb.writeLog("--shcqOrg: " + shcqOrg);

                    String shcqCostnumber = salary.get("shcq_costnumber");
//                    bb.writeLog("--shcqCostnumber: " + shcqCostnumber);

                    String shcqCostname = salary.get("shcq_costname");
//                    bb.writeLog("--shcqCostname: " + shcqCostname);

                    String shcqCostorg = salary.get("shcq_costorg");
//                    bb.writeLog("--shcqCostorg: " + shcqCostorg);

                    String shcqAscription = salary.get("shcq_ascription");
//                    bb.writeLog("--shcqAscription: " + shcqAscription);

                    String shcqXcxm = salary.get("shcq_xcxm");
//                    bb.writeLog("--shcqXcxm: " + shcqXcxm);

                    List<Map<String, String>> shcqEntryentityList = new ArrayList<>();
                    Map<String, String> shcqEntryentityMap = new HashMap<>();
                    shcqEntryentityMap.put("shcq_amount", shcqAmount);
                    shcqEntryentityMap.put("shcq_costnumber", shcqCostnumber);
                    shcqEntryentityMap.put("shcq_costname", shcqCostname);
                    shcqEntryentityMap.put("shcq_costorg", shcqCostorg);
                    shcqEntryentityMap.put("shcq_ascription", shcqAscription);
                    shcqEntryentityMap.put("shcq_xcxm", shcqXcxm);

                    shcqEntryentityList.add(shcqEntryentityMap);

                    subSalaryMap.put("number", number);
                    subSalaryMap.put("shcq_org", number);
                    subSalaryMap.put("shcq_totalamount", shcqAmount);
                    subSalaryMap.put("salary_acct_record_id", salaryAcctRecordId);
                    subSalaryMap.put("shcq_entryentity",shcqEntryentityList);

                    querydata.add(subSalaryMap);
                }
            }
        } catch ( Exception e ) {
            bb.writeLog("getSalaryInfo exception: " + e);
            result.put("success","false");
            result.put("message","请求异常，请联系管理员");
            return result;
        }

        bb.writeLog("--querydata: " + querydata);

        //将shcq_ascription、shcq_costorg、shcq_costnumber相同项中shcq_amount相加
        List<Map<String,Object>> newQueryData = new ArrayList<>();
        for (Map<String, Object>  qd: querydata) {
            Object entryentityObj = qd.get("shcq_entryentity");
            String shcqOrg = Util.null2String( qd.get("shcq_org"));
            String shcqTotalamount = Util.null2String(qd.get("shcq_totalamount"));
            String number = Util.null2String(qd.get("number"));
            if (entryentityObj != null) {
                List<Map<String,Object>> entryentity = (List<Map<String,Object>>) entryentityObj;
                Map<String, String> shcqEntryentityMap = new HashMap<>();
                for ( Map<String,Object> entity :entryentity) {
                    String ascription = Util.null2String( entity.get("shcq_ascription"));
                    String costorg = Util.null2String( entity.get("shcq_costorg"));
                    String costnumber = Util.null2String( entity.get("shcq_costnumber"));
                    String costname = Util.null2String( entity.get("shcq_costname"));
                    String xcxm = Util.null2String( entity.get("shcq_xcxm"));
                    String amount = Util.null2String( entity.get("shcq_amount"));

                    if ( !shcqEntryentityMap.containsKey("shcq_ascription:" + ascription + "|" + "shcq_costorg:"+ costorg + "|" +
                            "shcq_costnumber:"+ costnumber + "|" + "shcq_costname:" + costname + "|"+ "shcq_xcxm:" + xcxm)) {
                        shcqEntryentityMap.put("shcq_ascription:" + ascription + "|" + "shcq_costorg:"+ costorg + "|" +
                                "shcq_costnumber:"+ costnumber + "|" + "shcq_costname:" + costname + "|"+ "shcq_xcxm:" + xcxm, amount);
                    } else {
                        String oldAmount = Util.null2String( shcqEntryentityMap.get("shcq_ascription:" + ascription + "|" + "shcq_costorg:"+ costorg + "|" +
                                "shcq_costnumber:"+ costnumber + "|" + "shcq_costname:" + costname + "|"+ "shcq_xcxm:" + xcxm));
                        shcqEntryentityMap.put("shcq_ascription:" + ascription + "|" + "shcq_costorg:"+ costorg + "|" +
                                "shcq_costnumber:"+ costnumber + "|" + "shcq_costname:" + costname + "|"+ "shcq_xcxm:" + xcxm, String.valueOf( new BigDecimal(oldAmount).add(new BigDecimal(amount))));
                    }
                }
                List< Map<String, String>> tempList = new ArrayList<>();
                for ( String key : shcqEntryentityMap.keySet()) {
                    Map<String, String> tempMap = new HashMap<>();
                    String amount = shcqEntryentityMap.get(key);
                    String[] split = key.split("\\|");
                    for (String sp:split) {
                        String[] s = sp.split(":");
                        tempMap.put(s[0],s[1]);
                    }
                    tempMap.put("shcq_amount",amount);
                    tempList.add(tempMap);
                }
                Map<String, Object> tempEnMap = new HashMap<>();
                tempEnMap.put("number",number);
                tempEnMap.put("shcq_totalamount",shcqTotalamount);
                tempEnMap.put("shcq_org",shcqOrg);
                tempEnMap.put("shcq_entryentity",tempList);
                newQueryData.add(tempEnMap);
            }
//            String ascription = Util.null2String( qd.get("shcq_ascription"));
//            String costorg = Util.null2String( qd.get("shcq_costorg"));
//            String costnumber = Util.null2String( qd.get("shcq_costnumber"));
//            String costname = Util.null2String( qd.get("shcq_costname"));
//            String xcxm = Util.null2String( qd.get("shcq_xcxm"));
//            String amount = Util.null2String( qd.get("shcq_amount"));
//            for ( Map<String, Object>  qd1: querydata) {
//                String shcqAscription = Util.null2String(qd1.get("shcq_ascription"));
//                String shcqCostorg = Util.null2String(qd1.get("shcq_costorg"));
//                String shcqCostnumber = Util.null2String(qd1.get("shcq_costnumber"));
//                String shcqAmount = Util.null2String(qd1.get("shcq_amount"));
//                if ( ascription.equals(shcqAscription) && costorg.equals(shcqCostorg) && costnumber.equals(shcqCostnumber) ) {
//                    amount = String.valueOf( Double.parseDouble(amount) + Double.parseDouble(shcqAmount));
//                }
//            }
//            Map<String, Object> shcqEntryentityMap = new HashMap<>();
//            shcqEntryentityMap.put("shcq_amount", amount);
//            shcqEntryentityMap.put("shcq_costnumber", costnumber);
//            shcqEntryentityMap.put("shcq_costname", costname);
//            shcqEntryentityMap.put("shcq_costorg", costorg);
//            shcqEntryentityMap.put("shcq_ascription", ascription);
//            shcqEntryentityMap.put("shcq_xcxm", xcxm);
//            newQueryData.add(shcqEntryentityMap);
        }
        bb.writeLog("--newQueryData: " + newQueryData);

        for (Map<String, Object>  qd: newQueryData) {
            Object entryentityObj = qd.get("shcq_entryentity");
            bb.writeLog("--entryentityObj 排序中: " + entryentityObj);
            String shcqOrg = Util.null2String( qd.get("shcq_org"));
            String shcqTotalamount = Util.null2String(qd.get("shcq_totalamount"));
            String number = Util.null2String(qd.get("number"));
            if (entryentityObj != null) {
                List<Map<String,Object>> entryentity = (List<Map<String,Object>>) entryentityObj;
                // 使用Comparator对entryentity进行排序
                Collections.sort(entryentity, new Comparator<Map<String, Object>>() {
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        return ((String) o1.get("shcq_costnumber")).compareTo((String) o2.get("shcq_costnumber"));
                    }
                });
            }
        }

        bb.writeLog("--newQueryData 排序后: " + newQueryData);

        Map<String, Object> querydataMap = new HashMap<>();
        querydataMap.put("querydata",newQueryData);

        result.put("success","true");
        result.put("message",querydataMap);
        return result;
    }
}
